<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useVbenForm } from '#/adapter/form';
  import {attribute, getLayout} from '#/api';
  import { Page } from '@vben/common-ui';
  import { useRoute } from 'vue-router';
  import { message, Collapse, CollapsePanel,Button } from 'ant-design-vue';
  import {create,update} from '#/api';
  import dayjs from 'dayjs';
  import { useRouter } from 'vue-router';

  import { EBuilder, type PageSchema } from "epic-designer";

  const ebRef = ref<InstanceType<typeof EBuilder>>();
  const pageSchema = ref<PageSchema>({
    schemas: [
      {
        type: "page",
        id: "root",
        label: "页面",
        children: [
          {
            label: "表单",
            type: "form",
            icon: "epic-icon-daibanshixiang",
            componentProps: {
              layout: "horizontal",
              name: "default",
              labelWidth: 100,
              labelLayout: "fixed",
              labelCol: {
                span: 5,
              },
              wrapperCol: {
                span: 19,
              },
              hideRequiredMark: false,
              colon: true,
              labelAlign: "right",
              size: "middle",
              style: {
                width: "600px",
              },
            },
            children: [
              {
                label: "栅格布局",
                type: "row",
                icon: "epic-icon-zhage",
                children: [
                  {
                    type: "col",
                    children: [
                      {
                        label: "姓名",
                        type: "input",
                        field: "input_2drzm924",
                        icon: "epic-icon-write",
                        input: true,
                        componentProps: {
                          bordered: true,
                          placeholder: "请输入",
                        },
                        id: "input_2drzm924",
                      },
                    ],
                    componentProps: {
                      span: 12,
                    },
                    id: "col_m17ttkgz",
                  },
                  {
                    type: "col",
                    children: [
                      {
                        label: "年龄",
                        type: "number",
                        icon: "epic-icon-number",
                        field: "number_x4t431jb",
                        input: true,
                        componentProps: {
                          style: {
                            width: "100%",
                          },
                          placeholder: "请输入",
                        },
                        id: "number_x4t431jb",
                      },
                    ],
                    componentProps: {
                      span: 12,
                    },
                    id: "col_6uvxdrme",
                  },
                ],
                id: "row_fpuoo21a",
              },
              {
                label: "性别",
                type: "radio",
                icon: "epic-icon-danxuan-cuxiantiao",
                field: "radio_shndnr9b",
                input: true,
                componentProps: {
                  options: [
                    {
                      label: "男",
                      value: "男",
                    },
                    {
                      label: "女",
                      value: "女",
                    },
                  ],
                  optionType: "default",
                  defaultValue: "男",
                },
                id: "radio_shndnr9b",
              },
              {
                label: "兴趣",
                type: "checkbox",
                icon: "epic-icon-duoxuan1",
                field: "checkbox_1l91io8k",
                input: true,
                componentProps: {
                  options: [
                    {
                      label: "唱",
                      value: "唱",
                    },
                    {
                      label: "跳",
                      value: "跳",
                    },
                    {
                      label: "rap",
                      value: "rap",
                    },
                    {
                      label: "篮球",
                      value: "篮球",
                    },
                  ],
                },
                id: "checkbox_1l91io8k",
              },
              {
                label: "个人简介",
                type: "textarea",
                field: "textarea_1ihmowjl",
                icon: "epic-icon-edit",
                input: true,
                componentProps: {
                  placeholder: "请输入",
                  autoSize: {
                    minRows: 4,
                  },
                },
                id: "textarea_1ihmowjl",
              },
            ],
            id: "form_eifo73no",
          },
        ],
        componentProps: {
          style: {
            padding: "16px",
          },
        },
      },
    ],
    script:
      "const { defineExpose, find } = epic;\n\nfunction test (){\n    console.log('test')\n}\n\n// 通过defineExpose暴露的函数或者属性\ndefineExpose({\n test \n})",
  });




  const router = useRouter();


  // 使用 ref 来保存 Form 组件实例和 API
  const Form = ref(null);
  const FormApi = ref(null);
  const type1 = ref('');
  const className1 = ref('');
  const attrData = ref('')

  // 获取布局并更新 schema
  async function fetchLayout({type,className}) {
    try {
      const layoutResponse = await getLayout({
        type: type,
        classEntity:className,
      });
      const layoutJson = JSON.parse(layoutResponse.layoutJson); // 解析布局 JSON
      pageSchema.value = layoutJson;
    } catch (error) {
      message.error('获取布局失败');
    }
  }

  // 获取属性数据
  const getAttribute = async (pid: string) => {
    try {
      // 假设 attribute(pid) 返回的数据结构和你提供的 JSON 相同
      const res = await attribute(pid);
      attrData.value = res; // 保存获取到的数据
      // 提取 attrList 并格式化为适合表单的键值对
      let fieldValues = res.attrList.reduce((values, item) => {
        // 根据字段的数据类型进行格式化
        if (item.dataType === 'java.lang.Boolean') {
          values[item.attrName] = item.value =='true'||item.value ==true ? true:false;  // 将 Boolean 转换为 '是' 或 '否'
        } else if (item.dataType === 'java.util.Date') {
          if(item.value!=''){
            values[item.attrName] = dayjs(item.value);
          }
        } else {
          values[item.attrName] = item.value || '';  // 默认处理其他类型
        }
        return values;
      }, {});
      console.log("fieldValues11",fieldValues)
      const valus = transform(fieldValues)
      console.log("fieldValues",valus)
      ebRef.value?.setData(valus);
    } catch (error) {
      message.error('获取属性数据失败');
    }
  };

  function transform(obj: Record<string, any>): Record<string, any> {
    return Object.entries(obj).reduce((acc, [key, value]) => {
      if (key.endsWith("Id")) {
        const keyName = obj[key.replace("Id", "Key")]; // 获取对应的Key字段的值
        if (keyName) {
          acc[key] = `PR:${keyName}:${value}`;
        } else {
          acc[key] = value; // 没找到对应的Key，保持不变
        }
      } else if (typeof value === "boolean") {
        acc[key] = value.toString(); // 转换 boolean 为字符串
      } else {
        acc[key] = value;
      }
      return acc;
    }, {} as Record<string, any>);
  }
  // 组件挂载时获取布局
  onMounted(() => {
    const route = useRoute();
    const type:string = route.query.type;
    const className:string = route.query.className;
    const pid:string = route.query.pid;
    type1.value = type;
    className1.value = className;
    fetchLayout({type, className});
    console.log("route.query.type",route.query.type,type1)
    if(type==='UPDATE'){
      getAttribute(pid)
    }
  });

  // 表单提交函数
  function onSubmit(values: Record<string, any>) {
    values.className = className1.value;
    console.log("type1==='CREATE'",type1,type1==='CREATE')
    if(type1.value==='CREATE'){
      create(values).then(res=>{
        message.success({ content: `操作成功` });
        // 延时 2 秒后返回上一个页面
        setTimeout(() => {
          router.back();
        }, 2000);
      })
    } else {
      update(values).then(res=>{
        message.success({ content: `操作成功` });
        // 延时 2 秒后返回上一个页面
        setTimeout(() => {
          router.back();
        }, 2000);
      })
    }
  }

  async function handleValidate(){
    console.log("dddd",ebRef.value)
    const data = {...(await ebRef.value.validate())}
    console.log('formData.value',data);

    onSubmit(data);
  }
  async function handleReset() {
    // 获取表单实例
    const form = await ebRef.value?.getFormInstance();
    // 调用组件实例方法，参考ui from 提供的重置方法，本案例以Ant Design Vue为基础UI
    form?.resetFields();
  }


</script>

<template>
  <Page autoContentHeight="true">
    <Collapse activeKey="true">
      <CollapsePanel key="true" :header="type1 === 'CREATE' ? '创建' : '更新'">
        <EBuilder ref="ebRef" :pageSchema="pageSchema" />
        <div class="button-container">
          <Button  type="primary" @click="handleValidate">提交数据</Button>
          <Button  danger type="primary" @click="handleReset">重置数据</Button>
        </div>
      </CollapsePanel>
    </Collapse>
  </Page>
</template>

<style scoped>
  .button-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    gap: 10px; /* 按钮之间的间隔 */
  }
</style>
